﻿using MQTTTool.MyControls;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace electrical_machinery.Utils
{
    public class SerialPortSendUtil
    {
        public static SerialPort serialPort;
        //是否打开,
        static bool isOpen = false;
        public static string receivedMsg = null;
        //锁，确保线程安全
        private static readonly object _lock = new object(); //锁对象
        private static readonly object _lock1 = new object(); //锁对象
        public static List<byte> recivice = new List<byte>();

        //声明
        public event QueryData queryData;
        //委托
        public delegate void QueryData(List<byte> data);

        public SerialPortSendUtil(SerialPort serialPort)
        {
            SerialPortSendUtil.serialPort = serialPort;
        }
        static SerialPortSendUtil()
        {
        }
        ///串口连接
        public bool StartSerialPortMonitor(SerialPort sp)
        {
            serialPort = sp;//获取声明串口
            try
            {

                /*bs.m_SerialPort.ReadBufferSize = 24;*/

                // bool a = bs.m_SerialPort.IsOpen;
                //是否打开串口
                if (!serialPort.IsOpen)
                {
                    serialPort.Open(); //打开串口

                    //接收到的信息
                    serialPort.DataReceived -= SerialPort_DataReceived;
                    serialPort.DataReceived += SerialPort_DataReceived;

                    
                }
                else
                {

                    if (serialPort != null && serialPort.IsOpen)
                    {
                        //关闭串口
                        serialPort.Close();
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("串行端口打开失败,请检查是否被占用！", "提示信息");
                // System.Environment.Exit(0); //彻底退出应用程序   
                return false;
            }
        }
        
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            lock (_lock)
            {
                while (serialPort.BytesToRead > 0)
                {
                    byte[] asd = new byte[serialPort.BytesToRead];
                    serialPort.Read(asd, 0, asd.Length);
                    recivice.AddRange(asd);
                    receivedMsg += Encoding.ASCII.GetString(asd);

                    queryData?.Invoke(recivice);
                    LittleGenius.isImport = false;
                    Thread.Sleep(300);
                }
            }
        }
       

        internal static string ParseValue()
        {
            lock (_lock1)
            {
                while (recivice.Count <= 0)
                {
                    Thread.Sleep(5);
                }
                Thread.Sleep(20);
                var str = ASCIIEncoding.ASCII.GetString(recivice.ToArray());
                recivice.Clear();
                return str;
            }
        }
    }
}
